package com.liu.core;

import com.liu.util.XssUtil;
import redis.clients.jedis.params.Params;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName XssHttpServletRequestWrapper
 * @Author liuxin
 * @Date Created in 2023-02-02 12:50
 * @Version 1.0
 */

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final HttpServletRequest orgRequest;

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        orgRequest=request;
    }


    @Override
    public String getParameter(String name) {
        System.out.println("过滤器name启动");
        return XssUtil.xssEncode(super.getParameter(XssUtil.xssEncode(name)));
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        System.out.println("过滤器map启动");
        Map<String, String[]> parameterMap = super.getParameterMap();
        Map<String, String[]> newParameterMap = new HashMap<>(parameterMap.size());
        for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            //处理key标签
            String newKey = XssUtil.xssEncode(stringEntry.getKey());
            String[] params = stringEntry.getValue();
            String[] newParams = new String[params.length];
            for (int i = 0; i < params.length;i++){
                newParams[i] = XssUtil.xssEncode(params[i]);
            }
            newParameterMap.put(newKey,newParams);
//            newParameterMap.put(stringEntry.getKey(), stringEntry.getValue());
        }

        return newParameterMap;
    }

    @Override
    public String[] getParameterValues(String name) {
        System.out.println("过滤器Values启动");
        String[] parameterValues = super.getParameterValues(XssUtil.xssEncode(name));
        String[] newParameterValues = new String[parameterValues.length];
        for (int i = 0; i < parameterValues.length; i++) {
            newParameterValues[i] =XssUtil.xssEncode( parameterValues[i]);        }
        return newParameterValues;
    }

    //空出该方法，用于使用原本的request
    public HttpServletRequest getOrgRequest(){
        return orgRequest;
    }
}
